﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text;

namespace UrlsAndRoutes.Infrastructure {

    public static class MyHtmlHelper {

        public static MvcHtmlString TabbedMenu(this HtmlHelper helper, IEnumerable<MenuTab> tabs) {
            var route = helper.ViewContext.RequestContext.RouteData;
            var controller = route.GetRequiredString("controller");
            var action = route.GetRequiredString("action");

            /*string menu = "<ul id=\"menu\">";
                menu += "</ul>";
             MvcHtmlString result = MvcHtmlString.Create(menu);
            return result;
               menu += "<li>" +
                       helper.ActionLink(tab.Text, tab.Action, tab.Controller, new { @class = "selected" }) +
                        "</li>";
                menu += "<li>" +
                             helper.ActionLink(tab.Text, tab.Action, tab.Controller) + "</li>";

             */

            TagBuilder ul = new TagBuilder("ul");
            ul.Attributes.Add("id", "menu");
            ul.AddCssClass("clearfix");

            StringBuilder listBuilder = new StringBuilder();
            TagBuilder li = null;

            foreach (MenuTab tab in tabs) {
                li = new TagBuilder("li");
                if (controller == tab.Controller && action == tab.Action) {
                    li.AddCssClass("selected");
                }
                li.InnerHtml = helper.ActionLink(tab.Text, tab.Action, tab.Controller).ToString();
                listBuilder.Append(li.ToString());
            }
            ul.InnerHtml = listBuilder.ToString();
            return MvcHtmlString.Create(ul.ToString());
        }
    }

    public class MenuTab {

        private MenuTab(string text, string action, string controller) {
            Text = text;
            Action = action;
            Controller = controller;
        }

        public static MenuTab Create(string text, string action, string controller) {
            return new MenuTab(text, action, controller);
        }

        public string Text { get; private set; }
        public string Action { get; private set; }
        public string Controller { get; private set; }
    }
}